package tcpnetwork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 */
@SuppressWarnings({"all"})
public class TcpEchoServer {

    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port); // 绑定端口号
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器!");
        while (true){
            // 获取客户端连接
            Socket clientSocket = serverSocket.accept();
            // 处理多个客户端
            // 每次 accept 成功 都创建一个新的线程 由新线程负责 processConnection 方法
            Thread t = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s: %d] 客户端建立连接!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
        // 处理请求和响应
        try (InputStream inputStream = clientSocket.getInputStream()){
            try (OutputStream outputStream = clientSocket.getOutputStream()){
                // 循环处理每个请求分别返回响应
                Scanner scanner = new Scanner(inputStream);
                while (true){
                    // 1. 获取请求
                    if (!scanner.hasNext()){
                        System.out.printf("[%s: %d] 客户端断开连接!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
                        break;
                    }
                    // 使用 Scanner 更方便 也可以使用 InputStream 的 read
                    String request = scanner.next();
                    // 2. 根据请求计算响应
                    String response = process(request);
                    // 3. 把响应返回给客户端
                    // 为了方便起见，可以使用 PrintWriter 把 OutputStrenm 包裹一下
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    // 刷新缓冲区，否则可能客户端不能第一时间看到响应结果
                    printWriter.flush();

                    System.out.printf("[%s: %d] req: %s, resp: %s\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(), request, response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close(); // 释放资源
        }
    }

    // 回显
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
